package io.github.wanggit.antcms.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.wanggit.antcms.server.domain.AntArticle;
import io.github.wanggit.antcms.server.domain.AntArticleTag;
import io.github.wanggit.antcms.server.mapper.AntArticleTagMapper;
import io.github.wanggit.antcms.server.service.ArticleTagService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class ArticleTagServiceImpl extends ServiceImpl<AntArticleTagMapper, AntArticleTag>
        implements ArticleTagService {
    @Override
    public void saveOrUpdateRelations(List<Long> tagIds, AntArticle antArticle) {
        if (null == tagIds || null == antArticle) {
            return;
        }
        List<AntArticleTag> articleTags = new ArrayList<>();
        QueryWrapper<AntArticleTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", antArticle.getId());
        remove(queryWrapper);
        tagIds.forEach(
                it -> {
                    AntArticleTag articleTag = new AntArticleTag();
                    articleTag.setArticleId(antArticle.getId());
                    articleTag.setTagId(it);
                    articleTags.add(articleTag);
                });
        saveBatch(articleTags);
    }

    @Override
    public List<AntArticleTag> findRelationsByArticle(AntArticle article) {
        QueryWrapper<AntArticleTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", article.getId());
        return list(queryWrapper);
    }

    @Override
    public void deleteRelationsByArticle(AntArticle article) {
        QueryWrapper<AntArticleTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", article.getId());
        remove(queryWrapper);
    }
}
